package optimizer;

public class Instruction {
	String label;
	String op;
	Register writtenTo;
	Register readFrom1;
	Register readFrom2;
	int constant;
	String branchTarget;
	String originalInstruction;

	public Instruction(String instructionLine) {
		this.label = null;

		int indexOfColen = instructionLine.indexOf(":");
		if(indexOfColen > 0) {
			this.label = instructionLine.substring(0, indexOfColen);
			instructionLine = instructionLine.substring(indexOfColen);
		}
		else if(indexOfColen == 0){
			System.out.println("Error in Instruction constructor : Invalide instruction, Label has empty charactors");
		}

		int indexOfSpace = instructionLine.indexOf(" ");
		if(indexOfSpace > 0) {
			this.op = instructionLine.substring(0, indexOfSpace);
			instructionLine = instructionLine.substring(indexOfSpace);
		}
		else {
			System.out.println("Error in Instruction constructor : Invalide instruction, cannot identify the operation");
		}

		int indexOfComma = instructionLine.indexOf(",");
		if(indexOfSpace > 0) {
			this.writtenTo = matchRegister(instructionLine.substring(0, indexOfComma));
			instructionLine = instructionLine.substring(indexOfComma);
		}
		else {
			System.out.println("Error in Instruction constructor : Invalide instruction, cannot identify the register to be written");
		}

		indexOfComma = instructionLine.indexOf(",");
		if(indexOfSpace > 0) {
			this.readFrom1 = matchRegister(instructionLine.substring(0, indexOfComma));
			this.readFrom2 = matchRegister(instructionLine.substring(indexOfComma));
		}
		else {
			System.out.println("Error in Instruction constructor : Invalide instruction, cannot identify the registers to be read");
		}
	}
	
	
	
	public Instruction(String label, String op, Register writtenTo,
			Register readFrom1, Register readFrom2, int constant,
			String branchTarget, String originalInstruction) {
		super();
		this.label = label;
		this.op = op;
		this.writtenTo = writtenTo;
		this.readFrom1 = readFrom1;
		this.readFrom2 = readFrom2;
		this.constant = constant;
		this.branchTarget = branchTarget;
		this.originalInstruction = originalInstruction;
	}



	Register matchRegister(String reg) {
		Register r=null;
		if(reg == "R1") {
			r = Register.R1;
		}
		else if(reg == "R2") {
			r = Register.R2;
		}
		else if(reg == "R3") {
			r = Register.R3;
		}
		else if(reg == "R4") {
			r = Register.R4;
		}
		else if(reg == "R5") {
			r = Register.R5;
		}
		else if(reg == "R6") {
			r = Register.R6;
		}
		else if(reg == "R7") {
			r = Register.R7;
		}
		else if(reg == "R8") {
			r = Register.R8;
		}
		else {
			System.out.println("Error in Instruction constructor : Unknown register name, assuming it is a branch target and setting branch target");
			this.branchTarget = reg;
		}
		return r;
	}



}
